<template>

    <!--个人注册-->
    <div class="box-personalReg">
        <el-form :model="form" class="box-input" :rules="rules" ref="ruleFormRef" hide-required-asterisk="true">
            <el-form-item label="账号" prop="mobile">
                <el-input v-model="form.mobile" placeholder="请输入手机号" />
            </el-form-item>

            <el-form-item label="用户名" prop="name">
                <el-input v-model="form.name" placeholder="请输入用户名" />
            </el-form-item>

            <el-form-item label="所属单位" prop="unit_id" class="box-input-Subordinate">
                <el-select v-model="form.unit_id" filterable placeholder="请选择所属单位">
                    <el-option v-for="item in DataRequest" :key="item.id" :label="item.unit_name" :value="item.id" />

                </el-select>
            </el-form-item>

            <el-form-item label="密码" prop="password">
                <el-input @input="losePassword" v-model="form.password" placeholder="请输入密码" clearable show-password />
            </el-form-item>

            <el-form-item label="确认密码" prop="qrpassword">
                <el-input v-model="form.qrpassword" placeholder="请再次确认密码" clearable show-password />
            </el-form-item>


            <el-form-item label="验证码" prop="sms_code" class="box-input-butt">
                <div class="box-input-div">
                    <el-input v-model="form.sms_code" placeholder="请输入验证码" />
                    <span @click='sendCode' class="code"> {{ timer === 0 ? "发送验证码" : `${timer}秒后发送` }} </span>
                </div>
            </el-form-item>

        </el-form>

        <div class="box-but">
            <!--checked 当前是否勾选 -->
            <input type="checkbox" :checked="agreement" @click="agreementBut" style="cursor: pointer;" />
            <p>已阅读并同意青海无人机综合管理服务平台 <span>《用户协议》</span>
            </p>
        </div>

        <el-form-item>
            <el-button type="primary" @click="onSubmit(ruleFormRef)">注册</el-button>
        </el-form-item>

        <div class="box-link">
            <router-link to="/login" class="box-router-link">去登录</router-link>
        </div>


    </div>

</template>


<script lang='ts' setup>

import { onMounted, reactive, ref, type Ref } from 'vue'

import Img from '@/assets/img/unitReg/pic_1.7fa36641.png'
import Image from '@/assets/img/unitReg/pic_2.bcbfbfa4.png'
import type { FormRules } from 'element-plus/es/tokens/form';
import type { userType } from '@/hooks/type';
import { useIntervalFn } from '@vueuse/core'
import { ElMessage, type FormInstance } from 'element-plus';
import { reg } from '@/hooks/validate';
import { Http } from '@/api/api';
import { dataSearchList } from '@/hooks/requestHooks'
import { useRouter } from "vue-router";


const form = reactive<userType | any>({});
const ruleFormRef = ref<FormInstance | any>()
const { DataRequest } = dataSearchList();
const agreement = ref(false);
const router = useRouter();

// 协议点击
const agreementBut = () => {
    agreement.value = !agreement.value;
};

// 密码失焦事件
const losePassword = () => {
    if (reg.pwd.test(form.password) && reg.pwd.test(form.qrpassword)) {

        // 两个密码的正则通过了才会比较密码的一致性
        ruleFormRef.value?.validateField('password', () => null)
        ruleFormRef.value?.validateField('qrpassword', () => null)
    }
}

// 验证两次确认密码是否匹配
const validatePass = (rule: any, value: any, callback: any) => {  // value = dbpass 确认密码的值 
    if (reg.pwd.test(form.password)) {
        if (value != form.password) {
            callback(new Error("两次密码不匹配"))
        } else {
            callback()
        }
    } else {
        // 密码正则不通过 就调起密码的正则
        ruleFormRef.value.validateField("password", () => null)
    }
}


// 表单验证
const rules = reactive<FormRules>({
    mobile: [
        { required: true, message: "账号不能为空", trigger: "blur" },
    ],
    name: [{ required: true, message: "用户名不能为空", trigger: "blur" },],
    Subordinate: [{ required: true, message: "所属单位不能为空", trigger: "blur" },],
    password: [
        { required: true, message: "密码不能为空", trigger: "blur" },
        { pattern: reg.pwd, message: "请输入6-16位数字加字母密码" },
    ],
    qrpassword: [
        { required: true, message: "确认密码不能为空", trigger: "blur" },
        { validator: validatePass, }
    ],
    sms_code: [{ required: true, message: "验证码不能为空", trigger: "blur" },],
});


// 控制发送验证码的倒计时效果
const timer = ref(0)
const { pause, resume } = useIntervalFn(() => {
    //    每次定时任务 控制时间递减
    if (timer.value <= 0) {
        // 停止递减：停止定时器
        pause()
    } else {
        timer.value -= 1
    }
}, 1000, {
    // 首次是否自动启动定时任务：true（默认值，自动启动），false，不需要自动启动
    immediate: false,
    // 是否延时执行定时任务（false(默认值)，不延时；true表示延时）
    immediateCallback: false
})


// 发送验证码
const sendCode = async () => {
    if (!form.mobile) {
        ElMessage.error('请输入手机号')
    } else if (reg.phone.test(form.mobile)) {
        //开启定时效果
        if (timer.value === 0) {
            // 发送ajax请求 form.mobile是填写的手机号
            let res = await Http.smsValid({ mobile: form.mobile, action: 'register' }) as unknown as userType;

            timer.value = 8

            if (res.status == 0) {
                ElMessage({
                    message: res.message,
                    type: "success",
                });
            } else {
                ElMessage.error(res.message)
            }
            // 重启定时器
            resume();
        } else {
            return
        }
    } else {
        ElMessage({
            message: '请输入正确的手机号',
            type: 'warning',
        })
    }
}


// 注册
const onSubmit = (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    formEl.validate(async (valid: boolean) => {
        if (valid) {
            console.log(form);
            if (!agreement.value) {
                ElMessage({
                    message: "请先勾选用户协议",
                    type: "error",
                });
            } else {
                let res = ((await Http. personalReg(form)) as unknown) as userType;
                if (res.status == 0) {
                    router.push('/login')
                    ElMessage({
                        message:'注册成功',
                        type: "success",
                    });
                } else {
                    ElMessage({
                        message:res.message,
                        type: "warning",
                    });
                }
            }
        }
    });
};




</script>


<style lang='scss' scoped>
.box-personalReg {
    // width: 345px;
    margin: 0 auto;

    // input框样式
    .box-input {
        margin: 0 auto;
        width: 345px;

        ::v-deep .el-form-item {
            width: 100%;

            .el-form-item__label {
                font-size: 12px;
            }
        }

        .el-input {
            width: 260px;
        }

        ::v-deep .el-input__wrapper {
            height: 28px;
            font-size: 12px;
            background-color: rgb(245, 248, 250);
        }

        ::v-deep .el-form-item__content {
            margin: 0px !important;
            justify-content: flex-end;

            .el-select {
                width: 260px;
            }
        }

    }


    // 验证码
    .box-input-butt {
        ::v-deep .el-form-item__content {
            .el-input {
                width: 180px;
            }
        }

        .box-input-div {
            width: 260px;
            display: flex;

            .code {
                text-align: center;
                line-height: 30px;
                font-size: 12px;
                background-color: rgb(92, 122, 255);
                color: rgb(255, 255, 255);
                width: 90px;
                cursor: pointer;
                border-radius: 5px;
            }
        }

    }
    

    // 用户协议样式
    .box-but {
        width: 350px;
        display: flex;
        justify-content: center;
        align-items: center;
        margin: 10px auto;
        cursor: pointer;

        p {
            font-size: 13px;
            color: rgb(118, 118, 118);

            span {
                color: rgb(0, 0, 0);
            }
        }

    }


    // 确认按钮
    .el-button {
        background-color: rgb(81, 113, 255);
        width: 345px;
        height: 35px;
        line-height: 40px;
        font-size: 14px;
        margin: 0 auto;
        border: none;
    }

    ::v-deep .el-form-item__content {
        width: 260px;
        margin: 0px !important;

        // 正则提示的样式
        .el-form-item__error {
            width: 260px;
            left: unset;
        }
    }

    // 注册，找回
    .box-link {
        width: 345px;
        margin: 0 auto;
        text-align: center;

        .box-router-link {
            color: rgb(82, 82, 82);
            font-size: 14px;
        }
    }
}
</style>


<style>
/* 所属单位弹窗的样式 */
.el-select__popper {
    width: 260px;
}

.el-select-dropdown__item>span {
    font-size: 12px;
}
</style>